package org.adorsys.aderp.cash.work.encashment.redirect;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

public class ClientToAderpCash {

	@Resource
	private RedirectorBean redirectorBean;
	Logger logger = Logger.getLogger("client_to_aderp-cash_logger");

	public String getCashUrl(String url, HttpServletRequest httpServletRequest,
			HttpServletResponse response,
			CashRegItemComponent cashRegItemComponent,DataCollection dataCollection) {

		logger.log(Level.INFO, " preparing for redirection ... ");
		redirectorBean.setModuleCallingUrl(incommingRequest(httpServletRequest));
		logger.log(Level.INFO, " ready to redirect ... ");
		httpServletRequest.setAttribute("cashRegisterComponent", cashRegItemComponent);
		httpServletRequest.setAttribute("dataCollection", dataCollection);
		RedirectView redirectView = new RedirectView();
		return redirectorBean.getAderpCashUrl()
				+ "?moduleCallingUrlValue="
								+ encodeUrlPathSegment(redirectorBean.getModuleCallingUrl(), httpServletRequest);
	}
	
	String incommingRequest(HttpServletRequest request){
		return request.getRequestURI();
	}
	String encodeUrlPathSegment(String pathSegment,
			HttpServletRequest httpServletRequest) {
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {
		}
		return pathSegment;
	}
}
